<template>
  <div class="change-password-container">
    <NavBar>
      <template #default> 修改密码 </template>
    </NavBar>

    <div class="form-section">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px" class="password-form">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password placeholder="请输入原密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmNewPassword">
          <el-input v-model="passwordForm.confirmNewPassword" type="password" show-password placeholder="请再次输入新密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="isSubmitting" class="submit-button">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import NavBar from "../../components/common/NavBar.vue";
import { ref, reactive } from "vue";
import { ElMessage, ElForm, ElFormItem, ElInput, ElButton } from "element-plus";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/user";
import { updatePassword } from "@/api/UserApi"; // 假设这是你的API文件路径

const userStore = useUserStore();
const router = useRouter();
const passwordFormRef = ref(null);
const isSubmitting = ref(false);

const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmNewPassword: "",
});

const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入新密码"));
  } else if (value.length < 6) {
    callback(new Error("新密码不能少于6位"));
  } else {
    if (passwordForm.confirmNewPassword !== "") {
      passwordFormRef.value.validateField("confirmNewPassword");
    }
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入新密码"));
  } else if (value !== passwordForm.newPassword) {
    callback(new Error("两次输入的密码不一致!"));
  } else {
    callback();
  }
};

const passwordRules = reactive({
  oldPassword: [
    { required: true, message: "请输入原密码", trigger: "blur" },
  ],
  newPassword: [
    { required: true, validator: validatePass, trigger: "blur" },
  ],
  confirmNewPassword: [
    { required: true, validator: validatePass2, trigger: "blur" },
  ],
});

const submitForm = async () => {
  if (!passwordFormRef.value) return;

  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      isSubmitting.value = true;
      try {
        const userId = userStore.userInfo.userId;
        if (!userId) {
          ElMessage.error("用户信息缺失，无法修改密码。请尝试重新登录。");
          isSubmitting.value = false;
          return;
        }

        const data = {
          userId: userId,
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword,
        };

        const res = await updatePassword(data); // 调用后端API

        if (res.data.code === 1) { // 假设后端返回的code为1表示成功
          ElMessage.success("密码修改成功，请重新登录！");
          // 自动退出登录
          userStore.logout(); // 清除用户Store中的信息
          router.push("/login"); // 跳转到登录页
        } else {
          ElMessage.error(res.msg || "密码修改失败，原密码可能不正确！"); // 显示后端返回的错误信息
        }
      } catch (error) {
        console.error("修改密码失败:", error);
        ElMessage.error("修改密码失败，请稍后重试。");
      } finally {
        isSubmitting.value = false;
      }
    } else {
      ElMessage.warning("请检查输入项。");
      return false;
    }
  });
};
</script>

<style scoped>
.change-password-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-section {
  padding: 15px;
  background-color: #fff;
  margin: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.password-form {
  padding-top: 20px;
}

.submit-button {
  width: 100%;
  margin-top: 20px;
}
</style>